package com.im.server.general.manage.index.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.im.server.general.common.bean.User;
import com.im.server.general.common.bean.system.Menu;
import com.im.server.general.common.dao.UserDAO;
import com.im.server.general.common.dao.system.MenuDAO;
import com.im.server.general.common.dao.system.UserMenuDAO;
import com.im.server.general.manage.auth.manager.AuthManager;
import com.onlyxiahui.common.message.result.ResultMessage;

/**
 * date 2018-06-13 10:27:23<br>
 * description
 * 
 * @author XiaHui<br>
 * @since
 */
@Service
public class IndexService {

	@Resource
	UserDAO userDAO;
	@Resource
	AuthManager authManager;
	@Resource
	MenuDAO menuDAO;
	@Resource
	UserMenuDAO userMenuDAO;

	public ResultMessage login(String account, String password) {
		ResultMessage rm = new ResultMessage();
		try {
			if (StringUtils.isNotBlank(account) && StringUtils.isNotBlank(password)) {
				User user = userDAO.getUserByAccount(account);
				if (null != user) {
					String type=user.getType();
					if(User.type_root.equals(type)||User.type_admin.equals(type)){
						if (password.equals(user.getPassword())) {
							String userId = user.getId();
							String token = authManager.createToken(userId);
							authManager.putToken(token, userId);
							if (User.type_root.equals(type)) {// 如果是超级管理员，则拥有所有权限
								authManager.putAuth(token);
							}
							rm.put("user", user);
							rm.put("token", token);
						} else {
							rm.addWarning("003", "密码错误！");
						}
					}else{
						rm.addWarning("002", "账号不存在！");
					}
				} else {
					rm.addWarning("002", "账号不存在！");
				}
			} else {
				rm.addWarning("001", "请输入账号和秘密！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			rm.addError("500", "系统异常");
		}
		return rm;
	}

	public List<Menu> menuList(String userId, String token) {
		// List<Menu> list =new ArrayList<Menu>();
		// User user = userDAO.get(userId);
		// if(null!=user){
		// if (user.getType() == User.type_system) {//如果是超级管理员，则拥有所有权限
		// list =menuDAO.getAllMenuList();
		// }else{
		// list =userMenuDAO.getMenuListByUserId(userId);
		// }
		// }
		List<Menu> list = userMenuDAO.getMenuListByUserId(userId);
		List<String> keyList = new ArrayList<String>();

		for (Menu m : list) {
			String id = m.getId();
			keyList.add(id);
		}
		authManager.setPermission(token, keyList);
		return list;
	}

	public User getUser(String id) {
		User user = userDAO.get(id);
		return user;
	}
}
